/**
 * 2018年12月21日下午2:40:38
 * @author 谢进财
 */
package com.baihang.project.ds.task;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.util.TypeUtils;
import com.baihang.framework.dao.Record;
import com.baihang.framework.kit.DateKit;
import com.baihang.framework.kit.JsonKit;
import com.baihang.framework.kit.database.RedisKit;
import com.baihang.project.ds.common.CommonService;
import com.baihang.project.ds.dao.FangYuanDao;
import com.baihang.project.ds.model.FangYuanModel;
import com.baihang.project.ds.webSocket.handler.DsWebSocketHandler;

import redis.clients.jedis.Jedis;

/**
 * 任务调度器
 *
 */
@Component
public class DsTask {
	private static Logger logger = LoggerFactory.getLogger(DsTask.class);
	private Jedis jedis = RedisKit.getJedis();
	@Autowired
	private DsWebSocketHandler handler;
	@Autowired
	private FangYuanDao dao;
	@Autowired
	private CommonService service;
	/**
	 * 向客户端推送房源状态
	 */
	@Scheduled(cron="0/2 * * * * ?")
	public void pushFangYuanState() {
		/*List<Record>  list = dao.queryForRecordList("select D_ID as id,D_state as state,D_CollectionCount as dc,E_CollectionCount as ec,D_Monitor as monitor from room");
		String json = JsonKit.listToJson(list, 1);*/
		List<String> list = jedis.hvals("rooms");
		StringBuilder sb = new StringBuilder("[");
		for(int i=0;i<list.size();i++) {
			sb.append(list.get(i)+",");
		}
		sb.delete(sb.length()-1, sb.length());
		sb.append("]");
		String jsonResult = String.format("{\"code\":\"%s\",\"result\":%s}","001",sb.toString());
		try {
			handler.broadcast(new TextMessage(jsonResult));
		} catch (IOException e) {
			logger.info("推送消息失败");
			e.printStackTrace();
		}
		//System.err.println("10秒走一次");
	}
	/**
	 * 向客户端推送服务端时间
	 */
	@Scheduled(cron="0/1 * * * * ?")
	public void pushServerTime() {
		//4表示项目启动状态，在启动状态根据时间来更改项目状态
		if("4".equals(jedis.hmget("systemConfig","State").get(0))) {
		/*	String startTime = jedis.hmget("systemConfig","StartTime").get(0);
			Long startTimeLong = DateKit.parse(startTime,DateKit.Format_DateTime).getTime();
			Long nowLong = (new Date()).getTime();//当前时间
			Long shopTimeLong = Long.valueOf(jedis.hmget("systemConfig","ShoppingTime").get(0))*60*1000;//抢购以毫秒计算
			Long leftTime = startTimeLong+shopTimeLong-nowLong;//大于0表示还在抢购中
*/			
			if(service.checkOver()) {
				jedis.hset("systemConfig", "State", "6");//6表示项目时间到了，自然结束
			}
		}
		
		String serverTime = DateKit.getCurrentDateTime(DateKit.Format_DateTime3);
		String jsonResult = String.format("{\"code\":\"%s\",\"result\":\"%s\"}","004",serverTime);
		try {
			handler.broadcast(new TextMessage(jsonResult));
		} catch (IOException e) {
			logger.info("推送服务端时间消息失败");
			e.printStackTrace();
		}			
	}
	
	/**
	 * 清理未正常结束的购买行为，主要是客户在犹豫时间内，断网失去与服务端连接。造成房源无法复原，一直提示在预购中。
	 */
	@Scheduled(cron="0/60 * * * * ?")
	public void clearNoShopOverFy() {
		//dao.update(String.format("update room set D_state=0,D_Operation=null,D_EditTime='%s' where TIMESTAMPDIFF(SECOND ,D_EditTime,NOW())>60 and D_state=1",DateKit.getCurrentDate(DateKit.Format_DateTime)));		
		List<String> list = jedis.hvals("rooms");//取出所有房源
		for(int i=0;i<list.size();i++) {
			FangYuanModel model = JSON.parseObject(list.get(i), new TypeReference<FangYuanModel>() {});
			if(model.getD_state().equals("1")) {
				Long lastTimeLong = DateKit.parse(model.getD_EditTime(),DateKit.Format_DateTime).getTime();
				Long nowLong = (new Date()).getTime();//当前时间
				if(nowLong-lastTimeLong>60*1000) {
					model.setD_state("0");
					model.setD_Operation("后台撤销");
					model.setD_EditTime(DateKit.getCurrentDateTime(DateKit.Format_DateTime));
					TypeUtils.compatibleWithFieldName = true;
					jedis.hset("rooms", String.valueOf(model.getD_ID()), JSON.toJSONString(model));
				}
			}
		}
	}
}
